package com.sczmgk.hotline_pzh.photo;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.sczmgk.hotline_pzh.R;
import com.sczmgk.hotline_pzh.base.BaseActivity;
import com.sczmgk.hotline_pzh.constants.Constants;
import com.sczmgk.hotline_pzh.dialog.DialogFactory;
import com.sczmgk.hotline_pzh.photo.adapter.PhotoAlbumAdapter;
import com.sczmgk.hotline_pzh.photo.entity.PhotoAlbum;
import com.sczmgk.hotline_pzh.photo.entity.PhotoItem;
import com.sczmgk.hotline_pzh.utils.MyLog;

import org.apache.commons.lang.StringUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
 * 自定义的列表相册
 * @author bo
 *
 */
public class PhotoAlbumActivity extends BaseActivity implements OnClickListener {

	/**
     * 表示该Activity可以接受的参数
     * @author EX-LUOCHUN
     * @version [Android PABank C01, 2011-12-24]
     */
    public static class Param{
        /**
         * 容量大小
         */
        public static final String CHOOSE_MAX_SIZE = "choose_max_size";

    }
	/**
	 * listview
	 */
    private ListView mListView;
    /**
     * 相册列表集合
     */
    private List<PhotoAlbum> mAibumList;
    /**
     * 当前选择中的图片
     */
    private List<PhotoItem> mSelectPhotoList;
    /**
     * 最大选择数量
     */
    private int mChooseMaxSize=0;

    private PhotoAlbumAdapter mAdapter;

    /**
     * loadingdialog
     */
    private Dialog loginLoadingDialog;

    private final int REQUEST_CODE_SELECT_PHOTO = 1040;
  /**
   * 设置获取图片的字段信息
   *
   */

    private static final String[] STORE_IMAGES = {
    	/**
    	 * 显示名字
    	 */
            MediaStore.Images.Media.DISPLAY_NAME, 			// 显示的名
            /**
             * 纬度
             */
            MediaStore.Images.Media.LATITUDE, 				// 维度
            /**
             * 经度
             */
            MediaStore.Images.Media.LONGITUDE, 				// 经度
            /**
             * ID
             */
            MediaStore.Images.Media._ID, 					// id
            /**
             * dir id 目录
             */
            MediaStore.Images.Media.BUCKET_ID, 				// dir id 目录
            /**
             * dir name 目录名字
             */
            MediaStore.Images.Media.BUCKET_DISPLAY_NAME, 	// dir name 目录名字
            /**
             * 数据
             */
            MediaStore.Images.Media.DATA
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photoalbum);
        initBackgroundData();
        initData();
        initView();
        mAibumList = getPhotoAlbum();



        initHeadStyle();
    }

    /**
     * dissmiss 进度条
     */
    protected void dismissLoadingDialog() {
        if (loginLoadingDialog != null && loginLoadingDialog.isShowing()) {
            loginLoadingDialog.dismiss();
        }
    }

    /**
     * 弹出进度条
     * @param strResource
     */
    protected void showLoaddingDialog(int strResource) {
        if (loginLoadingDialog == null || !loginLoadingDialog.isShowing()) {
            loginLoadingDialog = DialogFactory.getLoadingDialog(this, strResource);
        }
        if (!loginLoadingDialog.isShowing()) {
            loginLoadingDialog.show();
        }
    }

    /**
     * 初始化需要后台加载的数据
     */
    private void initBackgroundData() {
        new LoadDataAsyncTask().execute();
    }

    /**
     * 初始化加载数据
     * @author luochun
     */
    class LoadDataAsyncTask extends AsyncTask<Void, Object, List<PhotoAlbum>> {


        @Override
		protected void onPreExecute() {
			super.onPreExecute();
			showLoaddingDialog(R.string.loading_tip);;
		}

		@Override
		protected List<PhotoAlbum> doInBackground(Void... params) {
			return getPhotoAlbum();
		}

		@Override
		protected void onPostExecute(List<PhotoAlbum> result) {
			super.onPostExecute(result);
			dismissLoadingDialog();
			if(result!=null&&result.size()>0){
				initView(result);
			}else{
				Toast.makeText(PhotoAlbumActivity.this, R.string.empty_photo, Toast.LENGTH_SHORT).show();
			}
		}

    }

    private void initData(){
        Intent intent = getIntent();
    	mChooseMaxSize=intent.getIntExtra(Param.CHOOSE_MAX_SIZE, PhotoActivity.CHOOSE_MAX_COUNT);
        //TODO 取得已选中的图片
        mSelectPhotoList = (List<PhotoItem>) intent.getSerializableExtra(Constants.SELECTED_PIC_LIST);
    }

    private void initView(){
    	mListView = (ListView) findViewById(R.id.album_listview);
    	mListView.setOnItemClickListener(aibumClickListener);
    }

    private void initView(List<PhotoAlbum> aibumList){
    	mAibumList = aibumList;
    	mAdapter = new PhotoAlbumAdapter(mAibumList, this);
        mListView.setAdapter(mAdapter);
    }

    /**
     * 初始化头部信息
     */
    private void initHeadStyle(){
    	setTitle(R.string.photo_album_title);
//        setRightBtnClickListener(this);
    }

    /**
     * 相册点击事件
     */
    OnItemClickListener aibumClickListener = new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            Intent intent = new Intent(PhotoAlbumActivity.this,PhotoActivity.class);
            intent.putExtra(Constants.SELECTED_PIC_LIST, (Serializable)mSelectPhotoList);
            intent.putExtra(PhotoActivity.Param.AIBUM_INFO, mAibumList.get(position));
            intent.putExtra(PhotoActivity.Param.CHOOSE_MAX_SIZE, mChooseMaxSize);
            startActivityForResult(intent,REQUEST_CODE_SELECT_PHOTO);
        }
    };

    /**
     * 方法描述：按相册获取图片信息
     *
     */
    private List<PhotoAlbum> getPhotoAlbum() {
    	//相册列表
        List<PhotoAlbum> aibumList = new ArrayList<PhotoAlbum>();
        //查询相册列表
        Cursor cursor = MediaStore.Images.Media.query(getContentResolver(),
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                STORE_IMAGES,
                null,
                MediaStore.Images.Media.DATE_ADDED+" DESC,"+MediaStore.Images.Media.DISPLAY_NAME+" DESC");//加入时间，显示名字降序排序
        //
        Map<String, PhotoAlbum> countMap = new LinkedHashMap<String, PhotoAlbum>();
        PhotoAlbum photoAlbum = null;
        if(cursor == null){
        	return aibumList;
        }
        while (cursor.moveToNext()) {
            int dataColumnIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
            String path = cursor.getString(dataColumnIndex);
            String id = cursor.getString(3);
            String dir_id = cursor.getString(4);
            String dir = cursor.getString(5);

            if(!StringUtils.isEmpty(path)&&!StringUtils.isEmpty(id)){
            	if (!countMap.containsKey(dir)) {
                    photoAlbum = new PhotoAlbum();
                    photoAlbum.setName(dir);
                    photoAlbum.setBitmap(Integer.parseInt(id));
                    photoAlbum.setCount("1");
                    photoAlbum.getBitList().add(new PhotoItem(Integer.valueOf(id),path));
                    countMap.put(dir, photoAlbum);
                } else {
                    photoAlbum = countMap.get(dir);
                    photoAlbum.setCount(String.valueOf(Integer.parseInt(photoAlbum.getCount()) + 1));
                    photoAlbum.getBitList().add(new PhotoItem(Integer.valueOf(id),path));
                }
            }
        }
        cursor.close();
        Iterable<String> it = countMap.keySet();
        for (String key : it) {
            aibumList.add(countMap.get(key));
        }
        return aibumList;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.btn_right_title:
            this.finish();
            break;
        default:
            break;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	MyLog.d(TAG,"onActivityResult    requestCode: "+requestCode+ "   resultCode: "+resultCode);
        if (resultCode == REQUEST_CODE_SELECT_PHOTO) {
        	PhotoAlbum changeAibum = (PhotoAlbum) data.getSerializableExtra(PhotoActivity.ResultParam.AIBUM_INFO);
        	@SuppressWarnings("unchecked")
			List<PhotoItem> changeSelectPhotoList = (List<PhotoItem>)data.getSerializableExtra(PhotoActivity.ResultParam.SELECT_PHOTO_LIST);
        	if(requestCode == REQUEST_CODE_SELECT_PHOTO){
        		//如果用户有选择图片
        		if(changeSelectPhotoList!=null&&changeSelectPhotoList.size()>0){
//        			String[] photoStrings = new String[changeSelectPhotoList.size()];
//        			for(int i=0;i<changeSelectPhotoList.size();i++){
//        				photoStrings[i] = changeSelectPhotoList.get(i).getPhotoPath();
//        				MyLog.i(TAG,"取得图片的路径： "+changeSelectPhotoList.get(i).getPhotoPath());
//            		}
//        			Intent intent = new Intent();
//        			intent.putExtra(PhotoActivity.ResultParam.SELECT_PHOTO_LIST, (Serializable) changeSelectPhotoList);
//        			setResult(RESULT_OK, intent);
//                    finish();
        		}
        		//如果用户没有选择图片
        		else{
        			MyLog.e(TAG, "用户没有选择照片--------");
//        			finish();
        		}

                Intent intent = new Intent();
                intent.putExtra(PhotoActivity.ResultParam.SELECT_PHOTO_LIST, (Serializable) changeSelectPhotoList);
                setResult(RESULT_OK, intent);
                finish();
        	}
        	//如果cancel了
        	else if(resultCode == Activity.RESULT_CANCELED){
        		//现在不支持跨相册选择 所以屏蔽掉
//        		mSelectPhotoList = changeSelectPhotoList;
//        		if(mAibumList!=null){
//        			for(int i=0;i<mAibumList.size();i++){
//        				PhotoAlbum albumItem = mAibumList.get(i);
//        				if(albumItem.equals(changeAibum)){
//        					mAibumList.remove(i);
//        					mAibumList.add(i, changeAibum);
//        				}
//        			}
//        			mAdapter.notifyDataSetChanged();
//        		}
        	}

        }
    }

	@Override
	public void handleMessage(Message msg) {

	}

    @Override
    public boolean getIsNeedLogin() {
        return true;
    }
}
